<?php
/**
*
* @package express
* @version $Id: rss_parser.php,v 2.000 2009/01/01 00:37:00 bb4dd Exp $
* @copyright (c) 2009 bb4dd
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*
*/

/**
* @ignore
*/
if (!defined('IN_PHPBB'))
{
	exit;
}

/**
*
* RSS Parser from lastRSS script
* Simple yet powerfull PHP class to parse RSS files.
*
* @version lastRSS 0.9.1 2004-10-26
* @copyright 2004 http://lastrss.webdot.cz/
* @author Vojtech Semecky
*
* Modified by bb4dd
*
* @package express
*/
class rss_parser
{
	// Public properties
	var $default_cp = 'UTF-8';
	var $cdata = 'nochange';
	var $cp = '';
	var $items_limit = 0;
	var $strip_html = false;
	var $date_format = '';

	// Private variables
	var $channel_tags = array ('title', 'link', 'description', 'language', 'copyright', 'managingEditor', 'webMaster', 'lastBuildDate', 'rating', 'docs');
	var $item_tags = array('title', 'link', 'description', 'author', 'category', 'comments', 'enclosure', 'guid', 'pubDate', 'source');
	var $image_tags = array('title', 'url', 'link', 'width', 'height');
	var $textinput_tags = array('title', 'description', 'name', 'link');

	// Parse RSS file and returns associative array.
	function get($rss_url)
	{
		// If cache enabled
		if ($this->cache_dir != '')
		{
			$cache_file = $this->cache_dir . '/rss_' . md5($rss_url);
			$timedif = @(time() - filemtime($cache_file));

			if ($timedif < $this->cache_time)
			{
				// Cached file is fresh enough, return cached array
				$result = unserialize(join('', file($cache_file)));

				// Set 'cached' to true only if cached file is correct
				if ($result)
				{
					$result['cached'] = true;
				}
			}
			else
			{
				// Cached file is too old, create new
				$result = $this->parse($rss_url);
				$serialized = serialize($result);

				if ($f = @fopen($cache_file, 'w'))
				{
					fwrite($f, $serialized, strlen($serialized));
					fclose($f);
				}

				if ($result)
				{
					$result['cached'] = false;
				}
			}
		}
		// If cache disabled: load and parse the file directly
		else
		{
			$result = $this->parse($rss_url);

			if ($result)
			{
				$result['cached'] = false;
			}
		}

		return $result;
	}

	// Modification of preg_match(); return trimed field with index 1
	// from 'classic' preg_match() array output
	function my_preg_match($pattern, $subject)
	{
		// Start regullar expression
		preg_match($pattern, $subject, $out);

		// If there is some result... process it and return it
		if (isset($out[1]))
		{
			// Process CDATA (if present)
			if ($this->cdata == 'content')
			{
				// Get CDATA content (without CDATA tag)
				$out[1] = strtr($out[1], array('<![CDATA[' => '', ']]>' => ''));
			}
			else if ($this->cdata == 'strip')
			{
				// Strip CDATA
				$out[1] = strtr($out[1], array('<![CDATA[' => '', ']]>' => ''));
			}

			// If code page is set convert character encoding to required
			if ($this->cp != '')
			{
				$out[1] = iconv($this->rsscp, $this->cp . '//TRANSLIT', $out[1]);
			}

			return trim($out[1]);
		}
		else
		{
			// If there is no result, return empty string
			return '';
		}
	}

	// Replace HTML entities &something; by real characters
	function un_html_entities($string)
	{
		// Get HTML entities table
		$trans_tbl = get_html_translation_table(HTML_ENTITIES, ENT_QUOTES);
		// Flip keys <==> values
		$trans_tbl = array_flip($trans_tbl);
		// Add support for &apos; entity (missing in HTML_ENTITIES)
		$trans_tbl += array('&apos;' => "'");

		// Replace entities by values
		return strtr($string, $trans_tbl);
	}

	// parse() is private method used by get() to load and parse RSS file.
	// Don't use parse() in your scripts - use get($rss_file) instead.
	function parse($rss_url)
	{
		// Open and load RSS file
		if ($f = @fopen($rss_url, 'r'))
		{
			$rss_content = '';

			while (!feof($f))
			{
				$rss_content .= fgets($f, 4096);
			}

			fclose($f);

			// Parse document encoding
			$result['encoding'] = $this->my_preg_match("'encoding=[\'\"](.*?)[\'\"]'si", $rss_content);

			// If document codepage is specified, use it
			if ($result['encoding'] != '')
			{
				// This is used in my_preg_match()
				$this->rsscp = $result['encoding'];
			}
			// Otherwise use the default codepage
			else
			{
				// This is used in my_preg_match()
				$this->rsscp = $this->default_cp;
			}

			// Parse channel info
			preg_match("'<channel.*?>(.*?)</channel>'si", $rss_content, $out_channel);

			foreach($this->channel_tags as $channel_tag)
			{
				$temp = $this->my_preg_match("'<$channel_tag.*?>(.*?)</$channel_tag>'si", $out_channel[1]);

				// Set only if not empty
				if ($temp != '')
				{
					$result[$channel_tag] = $temp;
				}
			}

			// If date_format is specified and lastBuildDate is valid
			if ($this->date_format != '' && ($timestamp = strtotime($result['lastBuildDate'])) !== -1)
			{
				// Convert lastBuildDate to specified date format
				$result['lastBuildDate'] = date($this->date_format, $timestamp);
			}

			// Parse textinput info
			preg_match("'<textinput(|[^>]*[^/])>(.*?)</textinput>'si", $rss_content, $out_textinfo);
	
			// This a little strange regexp means:
			// Look for tag <textinput> with or without any attributes, but skip truncated version <textinput/> (it's not beggining tag)
			if (isset($out_textinfo[2]))
			{
				foreach($this->textinput_tags as $textinput_tag)
				{
					$temp = $this->my_preg_match("'<$textinput_tag.*?>(.*?)</$textinput_tag>'si", $out_textinfo[2]);

					// Set only if not empty
					if ($temp != '')
					{
						$result['textinput_' . $textinput_tag] = $temp;
					}
				}
			}

			// Parse image info
			preg_match("'<image.*?>(.*?)</image>'si", $rss_content, $out_imageinfo);

			if (isset($out_imageinfo[1]))
			{
				foreach($this->image_tags as $image_tag)
				{
					$temp = $this->my_preg_match("'<$image_tag.*?>(.*?)</$image_tag>'si", $out_imageinfo[1]);

					// Set only if not empty
					if ($temp != '')
					{
						$result['image_' . $image_tag] = $temp;
					}
				}
			}

			// Parse items
			preg_match_all("'<item(| .*?)>(.*?)</item>'si", $rss_content, $items);

			$rss_items = $items[2];
			$i = 0;
			$result['items'] = array();// Create array even if there are no items

			foreach($rss_items as $rss_item)
			{
				// If number of items is lower then limit: parse one item
				if ($i < $this->items_limit || $this->items_limit == 0)
				{
					foreach($this->item_tags as $item_tag)
					{
						$temp = $this->my_preg_match("'<$item_tag.*?>(.*?)</$item_tag>'si", $rss_item);

						// Set only if not empty
						if ($temp != '')
						{
							$result['items'][$i][$item_tag] = $temp;
						}
					}

					// Strip HTML tags and other bullshit from <description>
					if ($this->strip_html && $result['items'][$i]['description'])
					{
						$result['items'][$i]['description'] = strip_tags($this->un_html_entities(strip_tags($result['items'][$i]['description'])));
					}

					// Strip HTML tags and other bullshit from <title>
					if ($this->strip_html && $result['items'][$i]['title'])
					{
						$result['items'][$i]['title'] = strip_tags($this->un_html_entities(strip_tags($result['items'][$i]['title'])));
					}

					// If date_format is specified and <pubDate> is valid
					if ($this->date_format != '' && ($timestamp = strtotime($result['items'][$i]['pubDate'])) !== -1)
					{
						// Convert <pubDate> to specified date format
						$result['items'][$i]['pubDate'] = date($this->date_format, $timestamp);
					}

					// Item counter
					$i++;
				}
			}

			$result['items_count'] = $i;

			return $result;
		}
		// Error in opening return false
		else
		{
			return false;
		}
	}
}

?>